'''
Parameters for types must correspond to:
http://tools.ietf.org/html/draft-zyp-json-schema-03
'''
import types

# TODO: Move to devel
def _jsonify(message_type):
    def f(param):
        if 'doc' in param.__json__:
            scope = message_type[0: message_type.find('.')]
            desc = param.__json__['doc']
            if desc.startswith('_'):
                bundle_key = '{}.{}'.format(scope, desc[1:])
                param.__json__['doc'] = _(bundle_key)
        return param.__json__
    return f


# TODO: Validation part needs refactor
def _dictionaryHandler(template, original, key=None):
    errorList = list()

    # TODO: use generator instead
    for k, v in original.iteritems():
        if k not in template:
            errorList.append(_error(k, 'validation.key_unrecognized'))
    for k, v in template.iteritems():
        if k not in original:
            errorList.append(_error(k, 'validation.key_not_exists'))
        else:
            errorList.extend(validate(v, original[k], k))
    return errorList


def _listHandler(template, original, key=None):
    errorList = list()

    if len(template) != len(original):
        errorList.append(_error('list', 'validation.different_number_of_items'))
    else:
        for i, v in enumerate(template):
            errorList.extend(validate(v, original[i]))

    return errorList


def _functionHandler(template, original, key=None):
    errorList = list()
    original, errorDict = template(original)

    if errorDict is not None and len(errorDict) != 0:
        if (key is not None):
            errorDict['param'] = key
        errorList.append(errorDict)

    return errorList

_validators = {types.DictionaryType: _dictionaryHandler,
               types.ListType: _listHandler,
               types.FunctionType: _functionHandler}


def validate(template, original, key=None):
    errorList = list()
    validateHandler = _validators.get(type(template))

    if validateHandler is not None:
        errorList.extend(validateHandler(template, original, key))

    return errorList

# TODO:
#
# PLEASE DO NOT REMOVE THIS COMMENTED PIECE OF CODE.
# Whole validation module will be refactored.
# ------------------------------------------------------------------------------
#    errorList = validation.validate(business_module.REQUEST, msg_util.get_request(data_packet))
#    if (errorList!=None and len(errorList)!=0):
#        return msg_util.validation_exception(data_packet, errorList);

